package com.sys.sysserver.interceptor;

import com.sys.sysserver.context.BaseContext;
import com.sys.sysserver.domain.constant.JwtClaimsConstant;
import com.sys.sysserver.domain.properties.JwtProperties;
import com.sys.sysserver.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
@RequiredArgsConstructor
public class UserInterceptor implements HandlerInterceptor {
    private final JwtProperties jwtProperties;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;
//        String token = request.getHeader(jwtProperties.getUserTokenName());
        String token = extractBearerToken(request);
        log.info("\n\nTOKEN:{}\n\n", token);
        try {
            log.info("\n\n开始JWT校验\n\n");
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("\n\n当前用户ID为:{}\n\n", userId);
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception e) {
            log.info("\n\n校验失败\n\n");
            response.setStatus(401);
            return false;
        }
    }

    public String extractBearerToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) return authHeader.substring(7);
        return null;
    }
}
